package com.csw.flink.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo07SavaPoint {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //创建配置文件对象
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    properties.setProperty("group.id", "csw9")
    properties.setProperty("auto.offset.reset", "earliest") //earliest：读取所有数据 latest：读取最新数据
    /**
      * 创建kafka消费者
      */
    val consumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String]("checkpoint", new SimpleStringSchema(), properties)


    /**
      * 读取kafka数据的source task是有状态的  (保存的是消费偏移量)
      *
      */
    val kafkaDS: DataStream[String] = env.addSource(consumer).uid("source")

    /**
      * 只有有状态的算子才需要设置uid
      * uid 用于识别算子，保证后面代码修改后还可以从checkpoint中恢复过来
      */
    kafkaDS.flatMap(_.split(",")).uid("flatMap")
      .filter(word => word != "null")
      .map((_, 1)).uid("map")
      .keyBy(_._1)
      .sum(1).uid("sum")
      .print()


    env.execute()

    /**
      * 触发savepoint：xshellmaster中
      * flink savepoint  任务id  保存路径  -yid yarnid
      * flink savepoint f7f55240f10d75bd1b14f191fb175c5d hdfs://master:9000/flink/savepoint -yid application_1622533422610_0006
      * 会在设置的路径下保存一个状态，要想修改代码后恢复到之前的状态只需要指定此路径
      */
  }
}
